package com.aim.Activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.aim.nada.VehicleBean;
import com.aim.util.NADAWebserviceUtil;

public class Details extends Activity implements OnClickListener {
	
	Context mC;
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	private static final int BARCODE_SCANNER_REQUEST_CODE = 4321;
	static EditText vinText, makeText, modelText, yearText, typeText, colorText, plateText, mileageText;
	static Spinner towSpinner;
	String nMake,nModel,nYear;
	TextView tv;
	ArrayList<String> matches;
	ArrayAdapter<String> matchAdapter;
	Button searchImage,scanImage,voiceImage;
	ProgressDialog progressDialog;
	
	private Handler handler = new Handler(){  
  	  
        @Override  
        public void handleMessage(Message msg) {  
           
        	if(msg.what ==0)
            {
            	progressDialog.dismiss();  

            	makeText.setText(nMake);
            	modelText.setText(nModel);
            	yearText.setText(nYear);
            	
            }
        	
            if(msg.what ==1)
            {
            	progressDialog.dismiss();  

            	Toast.makeText(mC, "No Vehicle Information found", Toast.LENGTH_LONG).show();
            	
            }
            
	          
        }
        };
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("Create", ""+ImpoundTab.impoundState);
        setContentView(R.layout.impounddetail);
        vinText = (EditText) findViewById(R.id.edittextvin);
        makeText = (EditText) findViewById(R.id.edittextmake);
		modelText = (EditText) findViewById(R.id.edittextmodel);
		yearText = (EditText) findViewById(R.id.edittextyear);
		typeText = (EditText) findViewById(R.id.edittexttype);
		colorText = (EditText) findViewById(R.id.edittextcolor);
		plateText = (EditText) findViewById(R.id.edittextplate);
		mileageText = (EditText) findViewById(R.id.edittextmileage);
		tv = (TextView) findViewById(R.id.TextView05);
		//WebServiceUtil.setContext(this);
		mC = this;
		
		towSpinner = (Spinner) findViewById(R.id.towspinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.tow_reasons, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        towSpinner.setAdapter(adapter);
        towSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
        
        
        searchImage = (Button) findViewById(R.id.imageView1);
        searchImage.setOnClickListener(this);
		scanImage = (Button) findViewById(R.id.imageView2);
		scanImage.setOnClickListener(this);
		voiceImage = (Button) findViewById(R.id.imageView3);
		voiceImage.setOnClickListener(this);
		
        if(ImpoundTab.impoundState != 0)
		{
		tv.setText(ImpoundTab.no+"");
		vinText.setText(ImpoundTab.vin);
		makeText.setText(ImpoundTab.make);
		modelText.setText(ImpoundTab.model);
		yearText.setText(ImpoundTab.year);
		typeText.setText(ImpoundTab.type);
		plateText.setText(ImpoundTab.plate);
		colorText.setText(ImpoundTab.color);
		mileageText.setText(ImpoundTab.mileage);
		
		if(ImpoundTab.tow!=null)
		if(ImpoundTab.tow.equals("1")||ImpoundTab.tow.equals("2")||ImpoundTab.tow.equals("3")||ImpoundTab.tow.equals("4"))
			towSpinner.setSelection(Integer.parseInt(ImpoundTab.tow));

		}
		
    }
    
    public void finish(){
    	
    	mC = null;
    	vinText = null;
    	makeText = null;
    	modelText = null;
    	yearText = null;
    	typeText = null;
    	colorText = null;
    	plateText = null;
    	mileageText = null;
    	towSpinner = null;
    	nMake = null;
    	nModel = null;
    	nYear = null;
    	tv = null;
    	matches = null;
    	matchAdapter = null;
    	searchImage = null;
    	scanImage = null;
    	voiceImage = null;
    	progressDialog = null;
    	
    	
    	super.finish();
    	
    }

    public static void setDetails(){
    	
    	ImpoundTab.vin= vinText.getText().toString();
    	ImpoundTab.make= makeText.getText().toString();
    	ImpoundTab.model= modelText.getText().toString();
    	ImpoundTab.year= yearText.getText().toString();
    	ImpoundTab.type= typeText.getText().toString();
    	ImpoundTab.color= colorText.getText().toString();
    	ImpoundTab.mileage= mileageText.getText().toString();
    	ImpoundTab.plate= plateText.getText().toString();
    	ImpoundTab.tow= towSpinner.getSelectedItemPosition()+"";

    }
    
    public void onClick(View v) {
    	if (v.equals(searchImage)) {
    		//should check if there is vin
    		
    		
            progressDialog = new ProgressDialog(mC);
            progressDialog.setButton("cancel", new DialogInterface.OnClickListener() {
            	 public void onClick(DialogInterface dialog, int i) {

            	  dialog.cancel();
            	 }
            	});
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            	 public void onCancel(DialogInterface dialog) {

            	  progressDialog.dismiss();
            	  
            	 }
            	});
        	progressDialog.setCancelable(true);
        	progressDialog.setMessage("Searching for Vin information, please wait!");

        	progressDialog.show();
    		
        	
        	new Thread(){
        		public void run(){
            		try {
						VehicleBean vehicleBean = NADAWebserviceUtil
						.callNadaDetailWebservice(vinText.getText().toString()
								.trim());
						if (vehicleBean.getVinNumber()!=null) {
						
							nMake = vehicleBean.getCarMake();
							nModel = vehicleBean.getModel();
							nYear = vehicleBean.getYear();
							handler.sendEmptyMessage(0);
						}
						else{
						
							 handler.sendEmptyMessage(1);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        			
        			
        		}
        	}.start();

		
		}
    	if (v.equals(scanImage)) {
    		try {

    			
    			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    			
    			intent.putExtra("SCAN_MODE", "ONE_D_MODE");
    			
    			startActivityForResult(intent, BARCODE_SCANNER_REQUEST_CODE);

    			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	if (v.equals(voiceImage)) {

    		voiceImage.setClickable(false);
    		   
    		  
            // Check to see if a recognition activity is present   
            PackageManager pm = getPackageManager();   
            List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);   
            if (activities.size() != 0)   
            {   


            	startVoiceRecognitionActivity();
            	
            	
                
            }   
            else   
            {   
            	
            	Toast.makeText(getApplicationContext(), "Voice Recognizer not present", Toast.LENGTH_LONG).show();

            	voiceImage.setClickable(true);

            }   
    		

    		
    	}
    		
	}
    private void startVoiceRecognitionActivity()   
    {   

        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);   
      
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);   
       
        
        
//        intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, new Long(20000));   
        intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, new Long(5000));
//        intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 5000);
      
        
        
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Read the Vin Number");   
        
        try {
			startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			voiceImage.setClickable(true);
		}   
		
		
    }
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        
 	   if (requestCode == BARCODE_SCANNER_REQUEST_CODE) {
	 	   
	 		   if (resultCode == Activity.RESULT_OK) {
	 			  String contents = intent.getStringExtra("SCAN_RESULT");
	 			 
//	 			  String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
	 			  if(contents!=null&&contents.startsWith("I"))
	 				  contents = contents.substring(1);
	 			  

 	            vinText.setText(contents);

 	      } else if (resultCode == Activity.RESULT_CANCELED) {
 	         Log.e("SEARCH_EAN", "CANCEL");
 	      }
 	      }

 	     
	 else if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)   
 	   {
		 voiceImage.setClickable(true);
 		  if (resultCode == Activity.RESULT_OK) {  
 			 matches = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);   
//             mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches));   
 			matchAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, matches);
    		
    		AlertDialog dlg = new AlertDialog.Builder(this)
            .setTitle("Choose correct Vin")
//            .setMessage("After Canceling all the infomation will be lost")
            .setSingleChoiceItems(matchAdapter, 0, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                    int pos) {
                // get selected item and close the dialog


                	String a = matches.get(pos).replace(" ","");
                	vinText.append(a);

                	dialog.dismiss();
                }})
            
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	dialog.dismiss();
                    /* User clicked cancel so do some stuff */
                }
            })
            .create();
            dlg.show();
 		  }   
 	   
 	   }
 	   
    }

}

